package domoticus;

import gnu.io.CommPortIdentifier;
import gnu.io.NRSerialPort;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Set;

public class ArduinoConnection {

    private OutputStream Output = null;
    SerialPort serialPort;
    private String PORT_NAME = "COM7";
    private static final int TIME_OUT = 2000;
    private static final int DATA_RATE = 9600;



    public void startConnection() throws IOException {


        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();

            if (PORT_NAME.equals(currPortId.getName())) {
                portId = currPortId;
                break;
            }
        }
        if (portId == null) {
            System.exit(0);
            return;
        }
        try {

            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);

            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            Output = serialPort.getOutputStream();


        } catch (PortInUseException | UnsupportedCommOperationException | IOException e) {

            System.exit(0);
        }
    }

    public void sentData(String data) {
        try {
            System.out.println(data);
                    
            Output.write(data.getBytes());
            
        } catch (Exception e) {
            System.out.println("Error al enviar datos");
        }

    }
     public synchronized void closeConnection() throws IOException {
        if (serialPort != null) {
            System.in.skip(System.in.available());
            serialPort.close();
            System.out.println("Puerto cerrado");
        } else {
            System.out.println("El puerto ya estaba cerrado");
        }
    }
}
